package com.example.poemtest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.poemtest.category.PoetryDynastyActivity;
import com.example.poemtest.category.UnlockDynastyDialog;
import com.example.poemtest.entity.DynastyToUserBean;
import com.example.poemtest.entity.DynastryPoetryBean;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * created by JHT on 2024/1/19
 * 分类页面fragment
 */
public class CategoryFragment extends Fragment implements View.OnClickListener {
    private View root;
    private ImageView imgSuo1, imgSuo2, imgSuo3, imgSuo4, imgSuo5, imgSuo6, imgSuo7, imgSuo8, imgSuo9, imgSuo10, imgSuo11;
    private ImageButton xianqin, lianghan, weijin, nanbeichao, suidai, tangdai, wudai, songdai, jinchao, yuandai, mingdai, qingdai;
    //解锁朝代的弹窗
    private UnlockDynastyDialog unlockDynastyDialog;
    private Button cancelUnlock, gradeUnlock, propUnlock;
    private List<ImageView> imageViewList = new ArrayList<>();
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    public static final int RESEND = 1, SEND = 2, SUCCESS = 3, CODEFALSE = 4, FALSE = 5;  //常量值
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            int flag = msg.arg1;
            if (flag == 0) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析数据
                        DynastryPoetryBean dynastyPoetry = com.alibaba.fastjson.JSONObject.parseObject(result, DynastryPoetryBean.class);
                        List<DynastryPoetryBean.DynastyPoetry> list = dynastyPoetry.getData();
                        if (Constant.poetryDynastyList.size() != 0) {
                            Constant.poetryDynastyList.clear();
                        }
                        for (DynastryPoetryBean.DynastyPoetry dynastyPoetry1 : list) {
                            Constant.poetryDynastyList.add(dynastyPoetry1);
                            Log.e("所有的朝代诗词",dynastyPoetry1.toString());
                        }
                    } else {
//                    Toast.makeText(RegisterActivity.this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 1) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析数据
                        DynastyToUserBean dynastyToUserBeans = com.alibaba.fastjson.JSONObject.parseObject(result,DynastyToUserBean.class);
                        List<DynastyToUserBean.DynastyToUser> list = dynastyToUserBeans.getData();
//                        if (Constant.userPoetryDynastyList.size() != 0) {
//                            Constant.userPoetryDynastyList.clear();
//                        }
                        for (DynastyToUserBean.DynastyToUser dynasty : list) {
                            Constant.userPoetryDynastyList.add(dynasty.getNum());
                        }
                    } else {
//                    Toast.makeText(RegisterActivity.this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 2) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        DynastyToUserBean dynastyToUserBeans = com.alibaba.fastjson.JSONObject.parseObject(result,DynastyToUserBean.class);
                        List<DynastyToUserBean.DynastyToUser> list = dynastyToUserBeans.getData();
                        if (Constant.userPoetryDynastyList.size() != 0) {
                            Constant.userPoetryDynastyList.clear();
                        }
                        for (DynastyToUserBean.DynastyToUser dynasty : list) {
                            Constant.userPoetryDynastyList.add(dynasty.getNum());
                        }
                    } else {
//                    Toast.makeText(LoginActivity.this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        FullScreenUtil.getInstance().fullScreen(getActivity(),true);
        root = inflater.inflate(R.layout.fragment_category, container, false);
//        Constant.userPoetryDynastyList.add(0);
        //获取朝代的诗词数据
        getCoon();
        getCoon2();
        //绑定控件对象
        setView();
        return root;
    }

    /**
     * 长按显示朝代
     */
    private void longListen(ImageButton imageButton, String dynasty) {
        imageButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(root.getContext(), dynasty,Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    /**
     * 绑定控件对象
     */
    private void setView() {
        xianqin = root.findViewById(R.id.xianqin);
        //长按显示朝代
        longListen(xianqin,"先秦");
        xianqin.setOnClickListener(this);
        lianghan = root.findViewById(R.id.lianghan);
        longListen(lianghan,"两汉");
        lianghan.setOnClickListener(this);
        weijin = root.findViewById(R.id.weijin);
        longListen(weijin,"魏晋");
        weijin.setOnClickListener(this);
        nanbeichao = root.findViewById(R.id.nanbeichao);
        longListen(nanbeichao,"南北朝");
        nanbeichao.setOnClickListener(this);
        suidai = root.findViewById(R.id.suidai);
        longListen(suidai,"隋代");
        suidai.setOnClickListener(this);
        tangdai = root.findViewById(R.id.tangdai);
        longListen(tangdai,"唐代");
        tangdai.setOnClickListener(this);
        wudai = root.findViewById(R.id.wudai);
        longListen(wudai,"五代");
        wudai.setOnClickListener(this);
        songdai = root.findViewById(R.id.songdai);
        longListen(songdai,"宋代");
        songdai.setOnClickListener(this);
        jinchao = root.findViewById(R.id.jinchao);
        longListen(jinchao,"金朝");
        jinchao.setOnClickListener(this);
        yuandai = root.findViewById(R.id.yuandai);
        longListen(yuandai,"元代");
        yuandai.setOnClickListener(this);
        mingdai = root.findViewById(R.id.mingdai);
        longListen(mingdai,"明代");
        mingdai.setOnClickListener(this);
        qingdai = root.findViewById(R.id.qingdai);
        longListen(qingdai,"清代");
        qingdai.setOnClickListener(this);
        imgSuo1 = root.findViewById(R.id.img_suo_1);
        imageViewList.add(imgSuo1);
        imgSuo2 = root.findViewById(R.id.img_suo_2);
        imageViewList.add(imgSuo2);
        imgSuo3 = root.findViewById(R.id.img_suo_3);
        imageViewList.add(imgSuo3);
        imgSuo4 = root.findViewById(R.id.img_suo_4);
        imageViewList.add(imgSuo4);
        imgSuo5 = root.findViewById(R.id.img_suo_5);
        imageViewList.add(imgSuo5);
        imgSuo6 = root.findViewById(R.id.img_suo_6);
        imageViewList.add(imgSuo6);
        imgSuo7 = root.findViewById(R.id.img_suo_7);
        imageViewList.add(imgSuo7);
        imgSuo8 = root.findViewById(R.id.img_suo_8);
        imageViewList.add(imgSuo8);
        imgSuo9 = root.findViewById(R.id.img_suo_9);
        imageViewList.add(imgSuo9);
        imgSuo10 = root.findViewById(R.id.img_suo_10);
        imageViewList.add(imgSuo10);
        imgSuo11 = root.findViewById(R.id.img_suo_11);
        imageViewList.add(imgSuo11);
        unlockDynastyDialog = new UnlockDynastyDialog(root.getContext());
        //遍历不需要加锁的朝代
        if (Constant.userPoetryDynastyList.size() != 0) {
            for (Integer i : Constant.userPoetryDynastyList) {
                imageViewList.get(Constant.userPoetryDynastyList.get(i)).setImageResource(0);
            }
        }
    }

    /**
     * 各个朝代图片的点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.xianqin:
                //跳转到先秦详细的朝代页面展示诗词
                testDynasty("先秦",0,0);
                break;
            case R.id.lianghan:
                //跳转到两汉详细的朝代页面展示诗词
                testDynasty("两汉",0,2);
                break;
            case R.id.weijin:
                //跳转到详细的朝代页面展示诗词
                testDynasty("魏晋",1,3);
                break;
            case R.id.nanbeichao:
                //跳转到南北朝详细的朝代页面展示诗词
                testDynasty("南北朝",2,4);
                break;
            case R.id.suidai:
                //跳转到隋代详细的朝代页面展示诗词
                testDynasty("隋代",3,5);
                break;
            case R.id.tangdai:
                //跳转到唐代详细的朝代页面展示诗词
                testDynasty("唐代",4,6);
                break;
            case R.id.wudai:
                //跳转到五代详细的朝代页面展示诗词
                testDynasty("五代",5,7);
                break;
            case R.id.songdai:
                //跳转到宋代详细的朝代页面展示诗词
                testDynasty("宋代",6,8);
                break;
            case R.id.jinchao:
                //跳转到金朝详细的朝代页面展示诗词
                testDynasty("金朝",7,9);
                break;
            case R.id.yuandai:
                //跳转到元代详细的朝代页面展示诗词
                testDynasty("元代",8,10);
                break;
            case R.id.mingdai:
                //跳转到明代详细的朝代页面展示诗词
                testDynasty("明代",9,11);
                break;
            case R.id.qingdai:
                //跳转到清代详细的朝代页面展示诗词
                testDynasty("清代",10,12);
                break;
            default:
                break;
        }
    }

    private void testDynasty(String dynasty, int num, int level) {
        boolean flag = true;
        for (Integer i : Constant.userPoetryDynastyList) {
            if (i == (Integer)num) {
                flag = false;
            }
        }
        Log.e("flag的值",flag + "");
        if (flag && !dynasty.equals("先秦")) {
            Log.e("得购买","购买");
            //若是没有解锁，弹出提示框，需要使用道具购买
            unlockDynastyDialog.show();
            cancelUnlock = unlockDynastyDialog.findViewById(R.id.cancel_unlock);
            gradeUnlock = unlockDynastyDialog.findViewById(R.id.grade_unlock);
            propUnlock = unlockDynastyDialog.findViewById(R.id.prop_unlock);
            //点击取消解锁按钮
            cancelUnlock.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //隐藏弹窗
                    unlockDynastyDialog.dismiss();
                }
            });
            //点击使用等级解锁按钮
            gradeUnlock.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //对比等级的大小，是否达到标准
//                    PoetryDynasty poetryDynasty = new PoetryDynasty();
//                    poetryDynasty.setDynastyName(dynasty);
//                    poetryDynasty.setDynastyGrade(1);
//                    Log.e("等级",Constant.userGrade+"");
//                            Log.e("String",unlockDynastyDialog.dialogGrade.getText().toString());
//                            Log.e("int",Integer.valueOf(unlockDynastyDialog.dialogGrade.getText().toString()).toString());
//                            int grade = Integer.valueOf(unlockDynastyDialog.dialogGrade.getText().toString());
                    if (Constant.userLevel > level || Constant.userLevel == level) {
                        //满足则解锁
                        //并将购买的朝代加入已购买的列表中,并将小锁图片隐藏，并修改后端数据
                        getCoon1(dynasty, num);
//                        Constant.suoList.add(num);
//                        imageViewList.get(num).setImageResource(0);
                        Intent intent1 = new Intent(CategoryFragment.this.getActivity(), PoetryDynastyActivity.class);
                        intent1.putExtra("Dynasty",dynasty + "名句");
                        startActivity(intent1);
                    } else {
                        Toast.makeText(CategoryFragment.this.getContext(),"当前等级不够，请继续学习提升您的等级！",Toast.LENGTH_SHORT).show();
                    }
                }
            });
            //点击使用道具解锁按钮
            propUnlock.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //检查是否有道具
                    if (Constant.myPropList.size() != 0) {
                        //并将购买的朝代加入已购买的列表中,并将小锁图片隐藏
//                        Constant.userPoetryDynastyList.add(dynasty);
//                        Constant.suoList.add(num);
//                        imageViewList.get(num).setImageResource(0);
                        getCoon1(dynasty, num);
                        //道具的数量减一
                        Constant.myPropList.remove(Constant.myPropList.size()-1);
                        Intent intent1 = new Intent(CategoryFragment.this.getActivity(), PoetryDynastyActivity.class);
                        intent1.putExtra("Dynasty",dynasty + "名句");
                        startActivity(intent1);
                    } else {
                        //没有道具，提示无道具，请先去购买道具！
                        Toast.makeText(CategoryFragment.this.getContext(),"无道具，请先去购买道具！",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            //如果已经购买了，就直接跳转到详细的朝代诗词页面
            Intent intent1 = new Intent(CategoryFragment.this.getActivity(), PoetryDynastyActivity.class);
            intent1.putExtra("Dynasty",dynasty + "名句");
            startActivity(intent1);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getCoon2();
        setView();
        //遍历不需要加锁的朝代
//        for (Integer i : Constant.userPoetryDynastyList) {
//            imageViewList.get(Constant.userPoetryDynastyList.get(i)).setImageResource(0);
//        }
    }

    /**
     * 获取网络连接
     * 查询所有朝代的诗
     */
    private void getCoon(){
        //获取朝代诗词信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/dynastyPoetry/findAll")        //改一下连接地址
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 0;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取网络连接
     */
    private void getCoon1(String dynasty, int num){
        //获取朝代诗词信息
//        JSONObject jsonObject = new JSONObject();
//        MediaType type = MediaType.parse("application/json;charset=utf-8");
//        Log.e("json请求",jsonObject.toString());
//        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/myDynasty/insertDynasty?userId=" + Constant.userId + "&dynasty=" + dynasty +"&num=" + num)        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 1;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取网络连接
     */
    private void getCoon2(){
        //查询已经解锁的朝代信息
        JSONObject jsonObject = new JSONObject();
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/myDynasty/findDynasty?userId=" + Constant.userId)        //改一下连接地址
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 2;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}
